package com.kyub.spring.gae;

import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.WebRequest;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.beans.PropertyEditorSupport;

/**
 * Created by IntelliJ IDEA.
 * User: sreghenzi
 * Date: 7-mag-2009
 * Time: 12.05.22
 * To change this template use File | Settings | File Templates.
 */
public class ClinicBindingInitializer  implements WebBindingInitializer {
    public void initBinder(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new
                CustomDateEditor(dateFormat, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
        binder.registerCustomEditor(Long.class, buildLongPropertyEditor());
        binder.registerCustomEditor(Boolean.class, buildBooleanPropertyEditor());
        binder.registerCustomEditor(Double.class, buildDoublePropertyEditor());

    }

    private PropertyEditorSupport buildLongPropertyEditor() {
        return new PropertyEditorSupport(){
            public void setAsText(String text) throws IllegalArgumentException {
               setValue(Long.decode(text));
            }
            public String getAsText() {
                final Object o = super.getValue();
                if (o == null)
                    return null;
                else
                    return o.toString();
            }
        };
    }

    private PropertyEditorSupport buildBooleanPropertyEditor() {
        return new PropertyEditorSupport(){
            public void setAsText(String text) throws IllegalArgumentException {
               setValue(Boolean.valueOf(text));
            }
            public String getAsText() {
                final Object o = super.getValue();
                if (o == null)
                    return null;
                else
                    return o.toString();
            }
        };
    }
     private PropertyEditorSupport buildDoublePropertyEditor() {
        return new PropertyEditorSupport(){
            public void setAsText(String text) throws IllegalArgumentException {
               setValue(Double.valueOf(text));
            }
            public String getAsText() {
                final Object o = super.getValue();
                if (o == null)
                    return null;
                else
                    return o.toString();
            }
        };
    }
}

